import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import WindiCSS from 'vite-plugin-windicss';
import createImportPlugin from 'vite-plugin-import';
import Components from 'unplugin-vue-components/vite';
import AutoImport from 'unplugin-auto-import/vite';
import { resolve } from 'path';
import { VarletUIResolver } from 'unplugin-vue-components/resolvers';
import { loadEnv } from 'vite';
import { pxToVw } from './build/vite/postcss.js';
// import { createStyleImportPlugin } from 'vite-plugin-style-import';
import OptimizationPersist from 'vite-plugin-optimize-persist';
import PkgConfig from 'vite-plugin-package-config';
import { createProxy } from './build/vite/proxy';

export default ({ mode }) =>
  defineConfig({
    base: loadEnv(mode, process.cwd()).VITE_PUBLIC_PATH,
    plugins: [
      vue(),
      WindiCSS(),
      createImportPlugin({
        onlyBuild: false, //是否只需要在生产环境中使用
        babelImportPluginOptions: [
          {
            libraryName: 'varlet',
            libraryDirectory: 'es',
            style: true, // or 'css'
          },
        ],
      }),
      // 自动导入css
      // createStyleImportPlugin({
      //   resolves: [],
      // }),
      AutoImport({
        imports: ['vue', 'vue-router', 'pinia'],
        // 第三方组件库的解析器
        // resolvers: [VarletUIResolver()],
        dts: 'src/auto-import.d.ts',
      }),
      Components({
        resolvers: [VarletUIResolver()],
        dirs: ['src/components'],
        extensions: ['vue'],
        dts: 'src/components.d.ts',
      }),
      // 启动优化
      PkgConfig(),
      OptimizationPersist(),
    ],
    resolve: {
      // 别名配置
      alias: {
        '@': resolve(__dirname, './src'),
        vue: 'vue/dist/vue.esm-bundler.js', // 定义vue的别名，如果使用其他的插件，可能会用到别名
      },
    },
    server: {
      // 配置代理
      proxy: {
        '/api': {
          target: 'http://127.0.0.1:8080',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, ''),
        },
      },
      open: true,
      port: JSON.parse(loadEnv(mode, process.cwd()).VITE_PORT),
      host: '0.0.0.0',
    },
    css: {
      preprocessorOptions: {
        // 开启使用内联JavaScript
        less: {
          javascriptEnabled: true,
        },
      },
      postcss: {
        plugins: [pxToVw],
      },
    },
    esbuild: {
      pure: ['console.log'],
      minify: true,
    },
    build: {
      rollupOptions: {
        output: {
          chunkFileNames: 'static/js/[name]-[hash].js',
          entryFileNames: 'static/js/[name]-[hash].js',
          assetFileNames: 'static/[ext]/[name]-[hash].[ext]',
          manualChunks(id) {
            if (id.includes('node_modules')) {
              return id.toString().split('node_modules/')[1].split('/')[0].toString();
            }
          },
        },
      },
    },
  });
